package com.ruoyi.web.controller.api;


import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.JsonFileToMapUtil;
import com.ruoyi.common.utils.OssUtils;
import com.ruoyi.common.utils.kimi.KimiStarBirthday;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.tt.ApiGetInfoUtil;
import com.ruoyi.kiku.domain.*;
import com.ruoyi.kiku.service.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.ruoyi.common.core.domain.AjaxResult.success;

/**
 * @author TT
 * @date 2025/3/4 15:06
 * @description DataController
 */
@RestController
@RequestMapping("/api")
public class DataController {
    @Autowired
    private IKikuWeiboDetailService weiboDetailService;
    @Autowired
    private IKikuWeiboTrumpetDetailService weiboTrumpetDetailService;
    @Autowired
    private IKikuMusicInfoService musicInfoService;
    @Autowired
    private IKikuFilmService filmService;
    @Autowired
    private IKikuRelationshipService relationshipService;
    @Autowired
    private IKikuWeiBoConcernService weiBoConcernService;

    @GetMapping("/weiboDetail")  //D:\weibo-crawler\weibo-crawler\weibo\鞠婧祎\3669102477.csv
    public void insertWeiboDetail() {
        try {
            // 打开 Excel 文件
            FileInputStream inputStream = new FileInputStream(new File("D:\\develop\\projects\\python\\weibo-crawler-master\\weibo\\鞠婧祎\\3669102477 (1).xlsx"));
            Workbook workbook = new XSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0); // 读取第一个工作表

            // 定义需要读取的列索引
            int[] columns = {14, 2, 4, 5, 9, 10, 11, 12};
            List<KikuWeiboDetail> kikuWeiboDetails = new ArrayList<>();

            // 遍历每一行，跳过第一行（表头）
            int rowIndex = 0;
            for (Row row : sheet) {
                if (rowIndex == 0) { // 跳过表头
                    rowIndex++;
                    continue;
                }

                KikuWeiboDetail detail = new KikuWeiboDetail();
                for (int col : columns) {
                    Cell cell = row.getCell(col); // 获取当前列的单元格
                    if (cell != null) {
                        // 根据单元格类型处理值

                        String cellValue = getCellValueAsString(cell);
                        // 根据列索引封装数据到 KikuWeiboDetail 对象
                        switch (col) {
                            case 2:
                                detail.setContent(cellValue); // 示例字段8
                                break;
                            case 4:
                                detail.setOriginalImageUrl(cellValue); // 示例字段2
                                break;
                            case 5:
                                detail.setVideoUrl(cellValue); // 示例字段3
                                break;
                            case 9:
                                detail.setLikeCount(parseLong(cellValue)); // 示例字段4
                                break;
                            case 10:
                                detail.setCommentCount(parseLong(cellValue)); // 示例字段5
                                break;
                            case 11:
                                detail.setRepostCount(parseLong(cellValue)); // 示例字段6
                                break;
                            case 12:
                                detail.setTopic(cellValue); // 示例字段7
                                break;
                            case 14:
                                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                                LocalDateTime dateTime = LocalDateTime.parse(cellValue, dateTimeFormatter);
                                ZonedDateTime zonedDateTime = dateTime.atZone(ZoneId.systemDefault());
                                Date date = Date.from(zonedDateTime.toInstant());
                                detail.setPublishDate(date); // 示例字段1
                                break;
                        }
                    }
                }
                kikuWeiboDetails.add(detail); // 将封装好的对象添加到列表
                rowIndex++;
            }

            // 打印封装后的数据
            for (KikuWeiboDetail detail : kikuWeiboDetails) {
                weiboDetailService.insertKikuWeiboDetail(detail);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/weiboTrumpetDetail")  //D:\weibo-crawler\weibo-crawler\weibo\鞠婧祎\3669102477.csv
    public void insertWeiboTrumpetDetail() {
        try {
            // 打开 Excel 文件
            FileInputStream inputStream = new FileInputStream(new File("C:\\Users\\Cecily\\Downloads\\3753348253.xlsx"));
            Workbook workbook = new XSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0); // 读取第一个工作表

            // 定义需要读取的列索引
            int[] columns = {14, 2, 4, 5, 9, 10, 11, 12};
            List<KikuWeiboTrumpetDetail> kikuWeiboDetails = new ArrayList<>();

            // 遍历每一行，跳过第一行（表头）
            int rowIndex = 0;
            for (Row row : sheet) {
                if (rowIndex == 0) { // 跳过表头
                    rowIndex++;
                    continue;
                }

                KikuWeiboTrumpetDetail detail = new KikuWeiboTrumpetDetail();
                for (int col : columns) {
                    Cell cell = row.getCell(col); // 获取当前列的单元格
                    if (cell != null) {
                        // 根据单元格类型处理值

                        String cellValue = getCellValueAsString(cell);
                        // 根据列索引封装数据到 KikuWeiboDetail 对象
                        switch (col) {
                            case 2:
                                detail.setContent(cellValue); // 示例字段8
                                break;
                            case 4:
                                detail.setOriginalImageUrl(cellValue); // 示例字段2
                                break;
                            case 5:
                                detail.setVideoUrl(cellValue); // 示例字段3
                                break;
                            case 9:
                                detail.setLikeCount(parseLong(cellValue)); // 示例字段4
                                break;
                            case 10:
                                detail.setCommentCount(parseLong(cellValue)); // 示例字段5
                                break;
                            case 11:
                                detail.setRepostCount(parseLong(cellValue)); // 示例字段6
                                break;
                            case 12:
                                detail.setTopic(cellValue); // 示例字段7
                                break;
                            case 14:
                                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                                LocalDateTime dateTime = LocalDateTime.parse(cellValue, dateTimeFormatter);
                                ZonedDateTime zonedDateTime = dateTime.atZone(ZoneId.systemDefault());
                                Date date = Date.from(zonedDateTime.toInstant());
                                detail.setPublishDate(date); // 示例字段1
                                break;
                        }
                    }
                }
                kikuWeiboDetails.add(detail); // 将封装好的对象添加到列表
                rowIndex++;
            }

            // 打印封装后的数据
            for (KikuWeiboTrumpetDetail detail : kikuWeiboDetails) {
                weiboTrumpetDetailService.insertKikuWeiboTrumpetDetail(detail);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @GetMapping("/musicInfo")  //D:\weibo-crawler\weibo-crawler\weibo\鞠婧祎\3669102477.csv
    public void insertMusicInfo() {
        try {
            // 打开 Excel 文件
            FileInputStream inputStream = new FileInputStream(new File("D:\\uibotProject\\网易云数据抓取\\res\\aa.xlsx"));
            Workbook workbook = new XSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0); // 读取第一个工作表

            // 定义需要读取的列索引
            int[] columns = {1,2,0};
            List<KikuMusicInfo> kikuMusicInfos = new ArrayList<>();

            // 遍历每一行，跳过第一行（表头）
            int rowIndex = 0;
            for (Row row : sheet) {
                // if (rowIndex == 0) { // 跳过表头
                //     rowIndex++;
                //     continue;
                // }

                KikuMusicInfo detail = new KikuMusicInfo();
                for (int col : columns) {
                    Cell cell = row.getCell(col); // 获取当前列的单元格
                    if (cell != null) {
                        // 根据单元格类型处理值

                        String cellValue = getCellValueAsString(cell);
                        // 根据列索引封装数据到 KikuWeiboDetail 对象
                        switch (col) {
                            case 0:
                                detail.setMusicName(cellValue); // 示例字段8
                                break;
                            case 1:
                                detail.setMusicAlias(cellValue); // 示例字段2
                                break;
                            case 2:
                                detail.setMusicDuration(cellValue); // 示例字段3
                                break;
                        }
                    }
                }
                kikuMusicInfos.add(detail); // 将封装好的对象添加到列表
                rowIndex++;
            }

            // 打印封装后的数据
            for (KikuMusicInfo detail : kikuMusicInfos) {
                musicInfoService.insertKikuMusicInfo(detail);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/filmInfo")  //D:\weibo-crawler\weibo-crawler\weibo\鞠婧祎\3669102477.csv
    public void insertFilmInfo() {
        try {
            // 打开 Excel 文件
            FileInputStream inputStream = new FileInputStream(new File("D:\\uibotProject\\film\\流程\\res\\film.xlsx"));
            Workbook workbook = new XSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0); // 读取第一个工作表

            // 定义需要读取的列索引
            int[] columns = {1,2,0,3,4,5};
            List<KikuFilm> kikuFilms = new ArrayList<>();

            // 遍历每一行，跳过第一行（表头）
            int rowIndex = 0;
            for (Row row : sheet) {
                // if (rowIndex == 0) { // 跳过表头
                //     rowIndex++;
                //     continue;
                // }

                KikuFilm detail = new KikuFilm();
                for (int col : columns) {
                    Cell cell = row.getCell(col); // 获取当前列的单元格
                    if (cell != null) {
                        // 根据单元格类型处理值

                        String cellValue = getCellValueAsString(cell);
                        // 根据列索引封装数据到 KikuWeiboDetail 对象
                        switch (col) {
                            case 0:
                                String type = removeFirstAndLastChar(cellValue);
                                detail.setType(type); // 示例字段8
                                //detail.setMusicName(cellValue); // 示例字段8
                                break;
                            case 1:
                                detail.setName(cellValue); // 示例字段8
                                //detail.setMusicAlias(cellValue); // 示例字段2
                                break;
                            case 2:
                                detail.setDoubanUrl(cellValue); // 示例字段2
                                // detail.setMusicDuration(cellValue); // 示例字段3
                                break;
                            case 3:
                                if (cellValue.contains("暂无评分") || cellValue.contains("尚未播出") || cellValue.contains("尚未上映")) {
                                    detail.setScore(new BigDecimal(0));
                                    break;
                                } else {
                                    System.out.println(cellValue);
                                    detail.setScore(new BigDecimal(cellValue));
                                    break;
                                }

                            case 4:
                                String[] strings = extractInfo(cellValue);
                                //detail.setName(strings[0]);
                                detail.setDirector(strings[1]);
                                detail.setReleaseTime(convertYearStringToDate(strings[3]));
                                break;
                            case 5:
                                detail.setIntroduction(cellValue); // 示例字段3
                                break;
                        }
                    }
                }
                    kikuFilms.add(detail); // 将封装好的对象添加到列表
                    rowIndex++;

            }

            // 打印封装后的数据
            for (KikuFilm detail : kikuFilms) {
                // musicInfoService.insertKikuMusicInfo(detail);
                 filmService.insertKikuFilm(detail);

            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 根据单元格类型获取值并转换为字符串
     * @param cell 单元格对象
     * @return 单元格值的字符串表示
     */
    private static String getCellValueAsString(Cell cell) {
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString(); // 如果是日期格式，返回日期字符串
                } else {
                    return String.valueOf(cell.getNumericCellValue()); // 返回数字的字符串表示
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula(); // 返回公式字符串
            default:
                return "Unknown cell type";
        }
    }
    private static Long parseLong(String value) {
        try {
            return Long.valueOf(value); // 尝试直接解析为 Long
        } catch (NumberFormatException e) {
            try {
                return Double.valueOf(value).longValue(); // 如果失败，尝试解析为 Double 并转换为 Long
            } catch (NumberFormatException ex) {
                System.err.println("Invalid number format: " + value);
                return null; // 或者返回默认值
            }
        }
    }
    public static String removeFirstAndLastChar(String str) {
        if (str == null || str.length() <= 2) {
            // 如果字符串为空或长度小于等于2，直接返回空字符串
            return "";
        }
        // 使用substring方法去掉第一个字符和最后一个字符
        return str.substring(1, str.length() - 1);
    }

    /**
     * 从字符串中提取信息
     * @param str
     * @return
     */
    public static String[] extractInfo(String str) {
        if (str == null || !str.startsWith("原名:")) {
            return new String[]{"", "", "", ""}; // 如果字符串为空或格式不正确，返回空字符串数组
        }

        // 去掉前缀"原名:"
        String content = str.substring(3);

        // 使用" / "分割字符串
        String[] parts = content.split(" / ");
        if (parts.length >= 4) {
            // 提取四个部分
            return new String[]{parts[0], parts[1], parts[2], parts[3]};
        } else {
            // 如果分割后的数组长度不足4，返回默认值
            return new String[]{"", "", "", ""};
        }
    }
    /**
     * 将字符串转换为日期对象
     * @param yearStr
     * @return
     */
    public static Date convertYearStringToDate(String yearStr) {
        if (yearStr == null || yearStr.length() != 4) {
            // 如果字符串为空或长度不是4位，返回null
            return null;
        }

        // 定义日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");

        try {
            // 将字符串转换为日期对象
            return sdf.parse(yearStr);
        } catch (ParseException e) {
            // 如果转换失败，捕获异常并返回null
            return null;
        }
    }
    @GetMapping("initRelationship")
    public AjaxResult initRelationshipData() throws Exception {
        FileInputStream file= null;
        try {
            file = new FileInputStream(new File("D:\\develop\\projects\\python\\FastAPIProject\\utils\\cecily\\baidu_baike_relations.xlsx"));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        ExcelUtil<KikuRelationship> util = new ExcelUtil<>(KikuRelationship.class);
        List<KikuRelationship> list = util.importExcel(file);
        for (int i = 0; i < list.size(); i++) {
            String name=list.get(i).getSocialName();
            Date birthdayByName = ApiGetInfoUtil.getBirthdayByName(name);
            System.out.println("name:"+name +" birthdayByName:"+birthdayByName);
            if (birthdayByName != null) {
                list.get(i).setSocialBirthdate(birthdayByName);
            }
            relationshipService.insertKikuRelationship(list.get(i));
        }
        //System.out.println(list);

        return success();
    }

    /**
     *  初始化微博关注列表
     * @return
     * @throws Exception
     */
    @GetMapping("initConcern")
    public AjaxResult initConcernData() throws Exception {
        List<Object> objects = JsonFileToMapUtil.jsonFileToList("D:\\develop\\projects\\python\\FastAPIProject\\utils\\cecily\\weibo_friends_3669102477.json");
        List<KikuWeiBoConcern> exportObject = new ArrayList<>();
        for (Object object : objects) {
            Map map = (Map) object;
            System.out.println("微博ID:"+map.get("id")+" 明星姓名:"+map.get("name")+" 工作地点:"+map.get("location")+" 描述:"+map.get("description")
            +" 粉丝数:"+map.get("followers_count"));
            KikuWeiBoConcern kikuWeiBoConcern = new KikuWeiBoConcern();
            kikuWeiBoConcern.setWeiboUserId(map.get("id").toString());
            kikuWeiBoConcern.setWeiboNickname(map.get("name").toString());
            kikuWeiBoConcern.setStarName(map.get("name").toString());
            kikuWeiBoConcern.setWorkplace(map.get("location").toString());
            kikuWeiBoConcern.setFansCount((Integer) map.get("followers_count"));
            kikuWeiBoConcern.setSelfIntroduction(map.get("description").toString());
            exportObject.add(kikuWeiBoConcern);

        }
        int result=weiBoConcernService.BatchInsertKikuWeiBoConcern(exportObject);
        return success(result);
    }
    /**
     * 上传文件测试
     */
    @PostMapping("/upload/ossTest")
    public AjaxResult upload(@RequestParam("file") MultipartFile file) {
        try {
            // 上传到OSS的upload/test目录下
            String url = OssUtils.upload(file, "upload/test");
            return AjaxResult.success("文件上传成功", url);
        } catch (Exception e) {
            return AjaxResult.error("文件上传失败：" + e.getMessage());
        }
    }
}
